<script lang="ts" setup>
import {
  cancelPatientOrderAPI,
  deletePatientOrderAPI,
  getPatientConsultOrderListAPI,
} from '@/apis/consult'
import {
  OrderStatus,
  type ConsultOrderItem,
  type GetPatientConsultOrderListParams,
} from '@/types/consult'
import { onShow } from '@dcloudio/uni-app'
import { ref } from 'vue'

// 接收父组件传递的参数
const props = defineProps<{
  type: number
}>()

// 定义查询参数
const query = ref<Required<GetPatientConsultOrderListParams>>({
  type: props.type, // 问诊类型
  current: 1, // 页码
  pageSize: 10, // 页大小
})

const list = ref<ConsultOrderItem[]>([])
const total = ref(0)
const pageTotal = ref(0)
const loadMoreStatus = ref<UniHelper.UniLoadMoreStatus>('loading')
// 是否显示查看更多
const activeShowMoreId = ref('')
// 获取订单列表
const getList = async (isMore = false) => {
  // 加载中
  loadMoreStatus.value = 'loading'
  const res = await getPatientConsultOrderListAPI(query.value)

  // 如果是加载更多，则追加数据
  if (isMore) {
    list.value.push(...res.data.rows)
  } else {
    list.value = res.data.rows
  }
  total.value = res.data.total
  pageTotal.value = res.data.pageTotal

  // 判断是否还有更多数据
  if (query.value.current < pageTotal.value) {
    loadMoreStatus.value = 'more'
  } else {
    loadMoreStatus.value = 'noMore'
  }
}
onShow(() => {
  getList()
})

// 加载更多数据
const getMoreData = async () => {
  // 如果当前页已经是最后一页，则不再加载
  if (query.value.current >= pageTotal.value) return
  // 页码加1
  query.value.current++
  // 加载更多数据
  await getList(true)
}
// 下拉刷新状态
const refresherTriggered = ref(false)
// 下拉刷新事件
const onRefresh = async () => {
  // 开启下拉刷新状态
  refresherTriggered.value = true
  // 重置页码
  query.value.current = 1
  // 重新加载数据
  await getList()
  // 关闭下拉刷新状态
  refresherTriggered.value = false
}

// 继续咨询
const handleContinueConsult = (item: ConsultOrderItem) => {
  console.log(item)
  uni.navigateTo({
    url: '/subpkg_consult/pages/room/room?orderId=' + item.id,
  })
}

// 删除订单
const handleDeleteOrder = async (id: string) => {
  const res = await uni.showModal({
    title: '提示',
    content: '确定删除该订单吗？',
    confirmColor: '#16c2a3',
  })
  if (res.confirm) {
    const res = await deletePatientOrderAPI(id)
    if (res.code === 10000) {
      uni.showToast({
        title: '删除成功',
      })
    }
    // 删除成功后，前端过滤掉该订单
    list.value = list.value.filter((item) => item.id !== id)
  }
}
// 取消订单
const handleCancelOrder = async (id: string) => {
  const res = await cancelPatientOrderAPI(id)
  if (res.code === 10000) {
    uni.showToast({
      title: '取消成功',
    })
  }
  // 取消成功后，前端更改此订单状态
  list.value.find((item) => item.id === id)!.status = OrderStatus.YiQuXiao
}
// 咨询其它医生
const handleConsultOtherDoctor = () => {
  uni.switchTab({
    url: '/pages/index/index',
  })
}
// 查看处方
const handleViewPrescription = () => {
  uni.previewImage({
    urls: ['https://yjy-teach-oss.oss-cn-beijing.aliyuncs.com/consult/%E5%A4%84%E6%96%B9.png'],
  })
}
// 去支付
const handlePayOrder = (id: string) => {
  uni.navigateTo({
    url: '/subpkg_consult/pages/order_detail/order_detail?orderId=' + id,
  })
}
</script>

<template>
  <scroll-view
    refresher-enabled
    refresher-background="#f6f6f6"
    class="uni-scroll-view"
    scroll-y
    @click="activeShowMoreId = ''"
    @scroll="activeShowMoreId = ''"
    @scrolltolower="getMoreData"
    :refresher-triggered="refresherTriggered"
    @refresherrefresh="onRefresh"
  >
    <view class="consult-list">
      <view class="consult-list-item" v-for="item in list" :key="item.id">
        <view class="consult-header">
          <view class="label">
            <image class="doctor-avatar" src="/static/uploads/doctor-avatar.jpg" />
            <text>{{ item.typeValue }}（自动分配医生）</text>
          </view>
          <text
            class="status"
            :class="{
              'color-1': item.status === OrderStatus.DaiZhiFu,
              'color-2': [OrderStatus.DaiJieZhen, OrderStatus.ZiXunZhong].includes(item.status),
              'color-3': [OrderStatus.YiWanCheng, OrderStatus.YiQuXiao].includes(item.status),
            }"
            >{{ item.statusValue }}</text
          >
        </view>
        <navigator
          class="consult-body"
          hover-class="none"
          :url="'/subpkg_consult/pages/order_detail/order_detail?orderId=' + item.id"
        >
          <uni-list :border="false">
            <uni-list-item :border="false" title="病情描述" :right-text="item.illnessDesc" />
            <uni-list-item :border="false" title="价格" :right-text="`¥ ${item.payment}`" />
            <uni-list-item :border="false" title="创建时间" :right-text="item.createTime" />
          </uni-list>
        </navigator>
        <view class="consult-footer">
          <view class="uni-button more" v-if="item.status === OrderStatus.YiWanCheng">
            <text
              class="label"
              @click.stop="activeShowMoreId = activeShowMoreId === item.id ? '' : item.id"
              >更多</text
            >
            <uni-transition :show="activeShowMoreId === item.id">
              <view class="list">
                <view class="list-item" @click="handleViewPrescription">查看处方</view>
                <view class="list-item" @click="handleDeleteOrder(item.id)">删除订单</view>
              </view>
            </uni-transition>
          </view>
          <template v-if="item.status === OrderStatus.DaiZhiFu">
            <button class="uni-button minor" @click="handleCancelOrder(item.id)">取消订单</button>
            <button class="uni-button" @click="handlePayOrder(item.id)">去支付</button>
          </template>

          <template v-if="item.status === OrderStatus.DaiJieZhen">
            <button class="uni-button minor" @click="handleCancelOrder(item.id)">取消订单</button>
            <button class="uni-button" @click="handleContinueConsult(item)">继续咨询</button>
          </template>

          <template v-if="item.status === OrderStatus.ZiXunZhong">
            <button class="uni-button" @click="handleContinueConsult(item)">继续咨询</button>
          </template>

          <template v-if="item.status === OrderStatus.YiWanCheng">
            <button class="uni-button minor" @click="handleContinueConsult(item)">问诊记录</button>
            <button v-if="item.evaluateId" class="uni-button minor">查看评价</button>
            <button v-else class="uni-button">去评价</button>
          </template>

          <template v-if="item.status === OrderStatus.YiQuXiao">
            <button class="uni-button minor" @click="handleDeleteOrder(item.id)">删除订单</button>
            <button class="uni-button" @click="handleConsultOtherDoctor">咨询其它医生</button>
          </template>
        </view>
      </view>
      <!-- 加载状态 -->
      <uni-load-more
        :status="loadMoreStatus"
        color="#C3C3C5"
        :icon-size="16"
        :content-text="{
          contentdown: '上拉显示更多',
          contentrefresh: '数据正在加载中',
          contentnomore: '没有更多数据了',
        }"
      />
    </view>
  </scroll-view>
</template>

<style lang="scss">
@import './styles.scss';
</style>
